<template>
  <div>
    <van-nav-bar
      title="用户注册"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />

    <div class="register-panel">
      <van-field
        v-model="username"
        label="用户名"
        icon="clear"
        placeholder="请输入用户名"
        :error-message="usernameErrorMsg"
        required
        @click-icon="username = ''"
      />

      <van-field
        v-model="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        :error-message="passwordErrorMsg"
        required
      />
      <div class="register-button">
        <van-button
          type="primary"
          size="large"
          @click="handleRegisterUser"
          :loading="openLoading"
          >马上注册</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '../api/user'
import { Toast } from 'vant'
export default defineComponent({
  setup() {
    const username = ref('')
    const password = ref('')
    const usernameErrorMsg = ref('')
    const passwordErrorMsg = ref('')
    const openLoading = ref(false)
    const router = useRouter()
    const goBack = () => {
      router.back()
    }
    const checkForm = () => {
      let isOk = true
      if (username.value.length < 5) {
        usernameErrorMsg.value = '用户名不能小于5位'
        isOk = false
      } else {
        usernameErrorMsg.value = ''
      }
      if (password.value.length < 6) {
        passwordErrorMsg.value = '密码不能少于6位'
        isOk = false
      } else {
        passwordErrorMsg.value = ''
      }
      return isOk
    }
    const handleRegisterUser = () => {
      if (checkForm()) {
        openLoading.value = true
        register({
          userName: username.value,
          password: password.value
        })
          .then((res) => {
            if (res.code === 200) {
              Toast.success(res.message)
              router.push('/')
            } else {
              openLoading.value = false
              Toast.fail(res.message)
            }
          })
          .catch((error) => {
            openLoading.value = false
            Toast.fail(error.message)
          })
      }
    }
    return {
      username,
      password,
      usernameErrorMsg,
      passwordErrorMsg,
      openLoading,
      goBack,
      handleRegisterUser
    }
  }
})
</script>

<style scoped>
.register-panel {
  width: 96%;
  border-radius: 5px;
  margin: 20px auto;
  padding-bottom: 50px;
}
.register-button {
  padding-top: 10px;
}
</style>